package com.jplus.core.utill;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.jplus.core.utill.Assert;
import com.jplus.core.utill.JUtil;
import com.jplus.core.utill.StreamUtil;

/**
 * SimpleSql
 */
public class SimpleSql {

    Map<String, String> sqlMap = new ConcurrentHashMap<>();

    public SimpleSql(String fileName) throws IOException {
        String sqls = new String(StreamUtil.toByteArray(ClassLoader.getSystemResourceAsStream(fileName)));
        List<String> sqlLine = Arrays.asList(sqls.split("\n"));
        String key = null;
        StringBuilder sql = new StringBuilder();
        for (String str : sqlLine) {
            if (str.startsWith("--")) {
                str = JUtil.trimAll(str);
                if (str.startsWith("--ID:")) {
                    if (key != null)
                        sqlMap.put(key, sql.toString());
                    key = str.substring(5);
                    sql.setLength(0);
                }
            } else {
                sql.append(str);
            }
        }
        if (key != null)
            sqlMap.put(key, sql.toString());
    }

    public String get(String key) {
        String sql = sqlMap.get(key);
        Assert.notNull(sql, "get sql is null:" + key);
        return sql;
    }

}